<?php
/***********************************************************
 * 字段逻辑定义
 * @作者 pcfcms <1131680521@qq.com>
 * @版权 广州市春风科技有限公司
 * @主页 http://www.pcfcms.com
 * @时间 2019年12月21日
***********************************************************/
namespace app\admin\logic;

use think\facade\Db;
use think\facade\Request;
use think\facade\Cache;

class FieldLogic 
{
    //初始化
    protected function initialize()
    {
        parent::initialize();
    }
    
    /**
     * 查询解析数据表的数据用以构造from表单
     * @param intval $channel_id 模型ID
     * @param intval $id 表主键ID
     */
    public function getTabelFieldList($channel_id, $id = '')
    {
        $global = get_global('global');
        $channel_id = intval($channel_id);
        $map = array(
            'channel_id'    => array('=', $channel_id),
            'ifsystem'      => 0,
        );
        $row = Db::name('channelfield')->where($map)->whereNotIn('name','id,aid,add_time,update_time')->select()->toArray();
        //编辑时显示的数据
        $addonRow = array();
        if (0 < intval($id)) {
            if ($global['arctype_channel_id'] == $channel_id) {
                $addonRow = Db::name('arctype')->field('*')->where('id', $id)->find();
            }
        }
        $list = $this->showViewFormData($row, 'addonField', $addonRow);
        return $list;
    }

    /**
     * 处理页面显示自定义字段的表单数据
     * @param array $list 自定义字段列表
     * @param array $formFieldStr 表单元素名称的统一数组前缀
     * @param array $addonRow 自定义字段的数据
     * @param array $archivesInfo 主表数据
     */
    public function showViewFormData($list, $formFieldStr, $addonRow = array(), $archivesInfo = [])
    {
        if (!empty($list)) {
            foreach ($list as $key => $val) {
                $val['fieldArr'] = $formFieldStr;
                switch ($val['dtype']) {
                    case 'int':
                    {
                        if (array_key_exists($val['name'], $addonRow)) {
                            $val['dfvalue'] = $addonRow[$val['name']];
                        } else {
                            if(preg_match("#[^0-9]#", $val['dfvalue']))
                            {
                                $val['dfvalue'] = "";
                            }
                        }
                        break;
                    }
                    case 'float':
                    case 'decimal':
                    {
                        if (array_key_exists($val['name'], $addonRow)) {
                            $val['dfvalue'] = $addonRow[$val['name']];
                        } else {
                            if(preg_match("#[^0-9\.]#", $val['dfvalue']))
                            {
                                $val['dfvalue'] = "";
                            }
                        }
                        break;
                    }
                    case 'select':
                    case 'radio':
                    {
                        $dfvalue = $val['dfvalue'];
                        $dfvalueArr = explode(',', $dfvalue);
                        $val['dfvalue'] = $dfvalueArr;
                        if (array_key_exists($val['name'], $addonRow)) {
                            $val['trueValue'] = explode(',', $addonRow[$val['name']]);
                        } else {
                            $dfTrueValue = !empty($dfvalueArr[0]) ? $dfvalueArr[0] : '';
                            $val['trueValue'] = array($dfTrueValue);
                        }
                        break;
                    }
                    case 'checkbox':
                    {
                        $dfvalue = $val['dfvalue'];
                        $dfvalueArr = explode(',', $dfvalue);
                        $val['dfvalue'] = $dfvalueArr;
                        if (array_key_exists($val['name'], $addonRow)) {
                            $val['trueValue'] = explode(',', $addonRow[$val['name']]);
                        } else {
                            $val['trueValue'] = array();
                        }
                        break;
                    }
                    case 'img':
                    {
                        $val[$val['name'].'_gzpcf_is_remote'] = 0;
                        $val[$val['name'].'_gzpcf_remote'] = '';
                        $val[$val['name'].'_gzpcf_local'] = '';
                        if (array_key_exists($val['name'], $addonRow)) {
                            if (is_http_url($addonRow[$val['name']])) {
                                $val[$val['name'].'_gzpcf_is_remote'] = 1;
                                $val[$val['name'].'_gzpcf_remote'] = handle_subdir_pic($addonRow[$val['name']]);
                            } else {
                                $val[$val['name'].'_gzpcf_is_remote'] = 0;
                                $val[$val['name'].'_gzpcf_local'] = handle_subdir_pic($addonRow[$val['name']]);
                            }
                        }
                        break;
                    }
                    case 'imgs':
                    {
                        $val[$val['name'].'_gzpcf_imgupload_list'] = array();
                        if (array_key_exists($val['name'], $addonRow) && !empty($addonRow[$val['name']])) {
                            $eyou_imgupload_list = explode(',', $addonRow[$val['name']]);
                            //支持子目录
                            foreach ($eyou_imgupload_list as $k1 => $v1) {
                                $eyou_imgupload_list[$k1] = handle_subdir_pic($v1);
                            }
                            $val[$val['name'].'_gzpcf_imgupload_list'] = $eyou_imgupload_list;
                        }
                        break;
                    }
                    case 'datetime':
                    {
                        $val['dfvalue'] = !empty($addonRow[$val['name']]) ? date('Y-m-d H:i:s', $addonRow[$val['name']]) : '';
                        break;
                    }
                    case 'htmltext':
                    {
                        $val['dfvalue'] = isset($addonRow[$val['name']]) ? $addonRow[$val['name']] : $val['dfvalue'];
                        //追加指定内嵌样式到编辑器内容的img标签，兼容图片自动适应页面
                        $title = '';
                        if (!empty($archivesInfo['title'])) {
                            $title = $archivesInfo['title'];
                        } else {
                            $title = !empty($archivesInfo['typename']) ? $archivesInfo['typename'] : '';
                        }
                        $content = htmlspecialchars_decode($val['dfvalue']);
                        $val['dfvalue'] = htmlspecialchars(img_style_wh($content, $title));
                        //支持子目录
                        $val['dfvalue'] = handle_subdir_pic($val['dfvalue'], 'html');
                        break;
                    }
                    default:
                    {
                        $val['dfvalue'] = array_key_exists($val['name'], $addonRow) ? $addonRow[$val['name']] : $val['dfvalue'];
                        //支持子目录
                        if (is_string($val['dfvalue'])) {
                            $val['dfvalue'] = handle_subdir_pic($val['dfvalue'], 'html');
                            $val['dfvalue'] = handle_subdir_pic($val['dfvalue']);
                        }
                        break;
                    }
                }
                $list[$key] = $val;
            }
        }
        return $list;
    }

    //获取全部字段类型
    public function getFieldTypeAll($field = '*', $index_key = '')
    {
        $cacheKey = "admin-Field-getFieldTypeAll-{$field}-{$index_key}";
        $result = cache::get($cacheKey);
        if (!empty($result)) {
            return $result;
        }
        $result = Db::name('field_type')->field($field)->order('sort_order asc')->select()->toArray();
        if (!empty($index_key)) {
            $result = convert_arr_key($result, $index_key);
        }
        cache::set($cacheKey, $result,PCFCMS_CACHE_TIME);//字段类型缓存
        return $result;
    }

    /**
     * 查询解析模型数据用以构造from表单
     * @param intval $channel_id 模型ID
     * @param intval $ifmain 是否主表、附加表
     * @param intval $aid 表主键ID
     * @param array $archivesInfo 主表数据
     */
    public function getChannelFieldList($channel_id, $ifmain = false, $aid = '', $archivesInfo = [],$suffix = "content")
    {
        $channel_id = intval($channel_id);
        $map = array();
        $map[] = ['channel_id','=',$channel_id];
        $map[] = ['ifmain','<>',1];
        $map[] = ['ifeditable','=',1];
        if (false !== $ifmain) {
            $map[] = ['ifmain','=',$ifmain];
        }
        $row = Db::name('channelfield')->where($map)->whereNotIn('name','id,aid,add_time,update_time')->order("sort_order asc")->select()->toArray();

        //编辑时显示的数据
        $addonRow = array();
        $map1 = array();
        $map1[] = ['typeid','=',$aid];
        $map1[] = ['channel','=',$channel_id];
        if (0 < intval($aid)) {
            if (6 == $channel_id) {
                $aid = Db::name('archives')->where($map1)->value('aid');
            }
            $tableExt = Db::name('channel_type')->where('id', $channel_id)->value('table');
            $suffix = explode(',',$suffix);
            foreach ($suffix as $val){
                $temp = Db::name($tableExt.'_'.$val)->field('*')->where('aid', $aid)->find();
                if(isset($temp)){
                  $addonRow = array_merge($addonRow,$temp);  
                } 
            }
        }
        $list = $this->showViewFormData($row, 'addonFieldExt', $addonRow, $archivesInfo);
        return $list;
    }

    //查询解析模型数据用以构造from表单
    public function dealChannelPostData($channel_id, $data = array(), $dataExt = array(),$suffix = 'content')
    {
        if (!empty($channel_id)) {
            $nowDataExt = array();
            $fieldTypeList = Db::name('channelfield')->where('channel_id', $channel_id)->column('name,dtype', 'name');
            foreach ($dataExt as $key => $val) {
                // 处理复选框取消选中的情况下
                if (preg_match('/^(.*)(_pcfempty)$/', $key) && empty($val)) {
                    $key = preg_replace('/^(.*)(_pcfempty)$/', '$1', $key);
                    continue;
                }
                $key = preg_replace('/^(.*)(_gzpcf_is_remote|_gzpcf_remote|_gzpcf_local)$/', '$1', $key);
                $dtype = !empty($fieldTypeList[$key]) ? $fieldTypeList[$key]['dtype'] : '';
                switch ($dtype) {
                    case 'checkbox':
                    {
                        $val = implode(',', $val);
                        break;
                    }
                    case 'switch':
                    case 'int':
                    {
                        $val = intval($val);
                        break;
                    }
                    case 'img':
                    {
                        $is_remote = !empty($dataExt[$key.'_gzpcf_is_remote']) ? $dataExt[$key.'_gzpcf_is_remote'] : 0;
                        if (1 == $is_remote) {
                            $val = $dataExt[$key.'_gzpcf_remote'];
                        } else {
                            $val = $dataExt[$key.'_gzpcf_local'];
                        }
                        break;
                    }
                    case 'imgs':
                    case 'files':
                    {
                        foreach ($val as $k2 => $v2) {
                            if (empty($v2)) {
                                unset($val[$k2]);
                                continue;
                            }
                            $val[$k2] = trim($v2);
                        }
                        $val = implode(',', $val);
                        break;
                    }
                    case 'datetime':
                    {
                        $val = !empty($val) ? strtotime($val) : 0;
                        break;
                    }
                    case 'decimal':
                    {
                        $moneyArr = explode('.', $val);
                        $money1 = !empty($moneyArr[0]) ? intval($moneyArr[0]) : '0';
                        $money2 = !empty($moneyArr[1]) ? intval(msubstr($moneyArr[1], 0, 2)) : '00';
                        $val = $money1.'.'.$money2;
                        break;
                    }
                    default:
                    {
                        $val = trim($val);
                        break;
                    }
                }
                if (!empty($val)){
                    $nowDataExt[$key] = $val;
                }else if($val == 0){ 
                    $nowDataExt[$key] = $val; // 判断是开关
                }else{
                    $nowDataExt[$key] = $val;
                }
            }
            $nowData = array(
                'aid'   => $data['aid'],
                'add_time'   => time(),
                'update_time'   => time(),
            );
            !empty($nowDataExt) && $nowData = array_merge($nowDataExt, $nowData);
            foreach ($nowData as $key => $value) {
                if(strpos($key,'_pcfempty')){
                    unset($nowData[$key]);
                }
            }
            $tableExt = Db::name('channel_type')->where('id', $channel_id)->value('table');
            $tableExt .= '_'.$suffix;
            $count = Db::name($tableExt)->where('aid', $data['aid'])->count();
            if (empty($count)) {
                Db::name($tableExt)->insert($nowData); // 添加
            } else {
                Db::name($tableExt)->where('aid', $data['aid'])->save($nowData); // 修改
            }
        }
    }
}